package com.nakamachizu.controller.mixi;

import java.util.Calendar;
import java.util.logging.Logger;

import org.apache.commons.lang.RandomStringUtils;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.datastore.Datastore;
import org.slim3.util.StringUtil;
import org.slim3.util.TimeZoneLocator;

import com.nakamachizu.meta.mixi.AssociateModelMeta;
import com.nakamachizu.model.mixi.AssociateModel;
import com.nakamachizu.model.session.MixiSessionData;
import com.nakamachizu.service.MapDataService;

public class AssociateController extends Controller {

    private static final Logger log = Logger.getLogger(AssociateController.class.getName());
    
    private String sid;
    private String key;
    private Calendar now;
    private String cmd; // release
    
    @Override
    public Navigation run() throws Exception {
        
        init();
        
        if(validate()){
            MapDataService mds = new MapDataService();
            MixiSessionData session = mds.getMixiSessionData(sid);
            if(StringUtil.isEmpty(cmd)){
                AssociateModelMeta meta = AssociateModelMeta.get();
                AssociateModel model = Datastore.query(meta).filter(meta.mixiId.equal(session.getViewerId())).asSingle();
                if(model == null){
                    model = new AssociateModel();
                    String accessKey = RandomStringUtils.randomAlphanumeric(16);
                    int i = 0;
                    while(Datastore.query(meta).filter(meta.accessKey.equal(accessKey)).countQuickly() > 0){
                        accessKey = RandomStringUtils.randomAlphanumeric(16);
                        i++;
                        if(i > 100){
                            throw new Exception("generate accesskey failed.");
                        }
                    }
                    model.setAccessKey(accessKey);
                    model.setEntryDate(now.getTime());
                    model.setMixiId(session.getViewerId());
                    model.setDisplayName(session.getViewerDisplayName());
                    key = accessKey;
                    
                    Datastore.put(model);
                }else{
                    key = model.getAccessKey();
                }
            }else{
                AssociateModelMeta meta = AssociateModelMeta.get();
                AssociateModel model = Datastore.query(meta).filter(meta.mixiId.equal(session.getViewerId())).asSingle();
                if(model != null){
                    Datastore.delete(model.getKey());
                }
            }
        }
        
        requestScope("key", key);
        
        return forward("/jsp/pc/mixi/associate.jsp");
    }
    
    private void init(){
        sid = requestScope("sid");
        cmd = requestScope("cmd");
        if(!StringUtil.isEmpty(cmd)){
            key = requestScope("key");
        }
        now = Calendar.getInstance(TimeZoneLocator.get());

    }
    
    protected boolean validate() {
        boolean result = false;
        Validators v = new Validators(request);
        v.add("sid", v.required());
        
        result = v.validate();
        
        return result;
    }
}
